export const loadNDJSON = async (
  url,
  renderCallback = () => {},
  sid = null,
  session_id,
  header = {}
) => {
  const items = []
  let buffer = ''
  let previousLine

  try {
    let response = await fetch(url, {
      method: 'post',
      headers: {
        ...header,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ front_session_id: session_id })
    })

    if (!response.ok) {
      renderCallback(
        {
          data: {
            content: 'error',
            isMarkdown: false
          }
        },
        sid
      )
      return items
    }

    const reader = response.body?.getReader()

    const decoder = new TextDecoder()
    let done = false

    while (!done) {
      const { value, done: readerDone } = await reader.read()
      done = readerDone

      if (value) {
        buffer += decoder.decode(value, { stream: true }) // 将新数据添加到缓冲区

        const lines = buffer.split('\n') // 按行分割

        buffer = lines.pop() || '' // 保留最后一行（可能不完整）

        for (const line of lines) {
          // 处理完整的行

          if (line.trim()) {
            // 跳过空行
            try {
              const Data = JSON.parse(line)
              const parsedData = JSON.parse(JSON.stringify(Data))

              items.push(parsedData)
              renderCallback(parsedData, sid)
              previousLine = line // 更新上一行
            } catch (e) {}
          }
        }
      }
    }
  } catch (error) {
    throw error
  }

  return items
}
